import os, json

from django.core import serializers
from django.http import HttpResponse, JsonResponse

from .models import Video, Url


def spider_video_url(request, douban_id):
    error_resp = HttpResponse('{"meta_status": "error", "meta_message": "无相关资源"}')
    try:
        video = Video.objects.get(video=douban_id)
    except Video.DoesNotExist:
        # https://movie.douban.com/subject/6874741/
        os.system("scrapy crawl mySpider -a douban_id=" + str(douban_id))
        try:
            video = Video.objects.get(video=douban_id)
        except Video.DoesNotExist:
            return error_resp

    if video is not None:
        try:
            urls = Url.objects.all().filter(video_id=video.id)
            data = serializers.serialize("json", urls)
            print(data)
            return HttpResponse('{"meta_status": "success", "data": '+ data +'}')
        except Url.DoesNotExist:
            return error_resp
    else:
        return error_resp